package com.example.parkingsharing

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.*
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.view.WindowCompat
import com.example.parkingsharing.data.User
import com.example.parkingsharing.ui.ParkingSharingApp
import com.example.parkingsharing.utils.getRandomString
import java.io.BufferedWriter
import java.io.IOException
import java.io.OutputStreamWriter

class MainActivity : ComponentActivity() {
    // 权限请求码
    private var mRequestCode = 1

    // 用户 ID
    var id = ""

    //请求的权限
    private val permissions = arrayOf(
        Manifest.permission.ACCESS_NETWORK_STATE,
        Manifest.permission.INTERNET,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.ACCESS_WIFI_STATE,
        Manifest.permission.ACCESS_FINE_LOCATION
    )

    private var isPermissionRequested = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val context = this

        // 处理 ID
        val sharedPreferences = this.getPreferences(MODE_PRIVATE)
        id = sharedPreferences.getString("id", "")!!
        if (id == "") {
            id = getRandomString(8)
            with(sharedPreferences.edit())
            {
                putString("id", id)
                apply()
            }
        }

        // 设置装饰适配系统窗口
        WindowCompat.setDecorFitsSystemWindows(window, false)
        setContent {
            ParkingSharingApp(context = context)
        }
        // 动态申请权限
        requestPermission(permissions)
    }

    private fun requestPermission(permissions: Array<String>) {
        if (Build.VERSION.SDK_INT >= 23 && !isPermissionRequested) {
            isPermissionRequested = true
            val permissionsList = ArrayList<String>()

            for (perm in permissions) {
                if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(perm)) {
                    // 进入到这里代表没有权限
                    permissionsList.add(perm)
                }
            }
            if (permissionsList.isNotEmpty()) {
                val strings = arrayOfNulls<String>(permissionsList.size)
                requestPermissions(permissionsList.toArray(strings), 0)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == mRequestCode) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // TODO("初始化地图")
            } else {
                Toast.makeText(
                    this@MainActivity,
                    "定位权限未授予！无法定位",
                    Toast.LENGTH_SHORT
                ).show()
            }
            return
        }
    }

    fun save(inputText: String) {
        try {
            val output = openFileOutput(User.USERID_FILE, Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(inputText)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}